package cn.geekyspace.scanhive.adapter.controller.fxml;

import cn.geekyspace.scanhive.domain.mapper.CleaningDataMapper;
import cn.geekyspace.scanhive.domain.entity.CleaningData;
import cn.geekyspace.scanhive.infrastructure.scanner.ScannerDataReceiver;
import cn.geekyspace.scanhive.domain.service.CleaningDataService;
import cn.geekyspace.scanhive.infrastructure.ui.UIScanTable;
import cn.geekyspace.scanhive.infrastructure.ui.UILogger;
import cn.geekyspace.scanhive.infrastructure.ui.UILastScanResult;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Data
@Slf4j
@Component
@RequiredArgsConstructor
public class ScanShowController {

    /*----------最近扫码结果----------*/
    // 扫码状态（OK/NG）
    @FXML
    private Label scanStatus;
    // 复制按钮
    @FXML
    public Button copyBtn;
    // 编辑按钮
    @FXML
    public Button editBtn;
    // 入库按钮
    @FXML
    public Button storageBtn;
    // 自动入库勾选框
    @FXML
    public CheckBox autoStorage;
    // 扫码结果
    @FXML
    private TextArea scanText;

    /*----------扫码记录----------*/
    // 扫码计数
    @FXML
    public Label scanCount;
    // 扫码结果表格
    @FXML
    public TableView<CleaningData> scanRecordTable;
    @FXML
    private TableColumn<CleaningData, String> idColumn;
    @FXML
    private TableColumn<CleaningData, String> qrCodeColumn;
    @FXML
    private TableColumn<CleaningData, Integer> cleaningDurationColumn;
    @FXML
    private TableColumn<CleaningData, Double> cleaningTemperatureColumn;
    @FXML
    private TableColumn<CleaningData, Integer> rinsingDurationColumn;
    @FXML
    private TableColumn<CleaningData, Double> rinsingTemperatureColumn;
    @FXML
    private TableColumn<CleaningData, Integer> dryingDurationColumn;
    @FXML
    private TableColumn<CleaningData, Double> dryingTemperatureColumn;
    @FXML
    private TableColumn<CleaningData, String> qrCodeScanTimeColumn;
    @FXML
    private TableColumn<CleaningData, String> plcDataReturnTimeColumn;

    // 注入UI组件
    private final UILogger uiLogger;
    private final UILastScanResult uiLastScanResult;
    private final UIScanTable uiScanTable;

    private final CleaningDataService cleaningDataService;
    private final CleaningDataMapper cleaningDataMapper;
    private final ScannerDataReceiver scannerDataReceiver;

    // 每页条数
    private static final int PAGE_SIZE = 20;

    @FXML
    public void initialize() {
        // 注入UI-最近扫码结果组件
        uiLastScanResult.setAutoStorage(autoStorage);
        uiLastScanResult.setScanText(scanText);
        uiLastScanResult.setScanStatus(scanStatus);
        // 注入UI-扫码记录组件
        uiScanTable.setScanCount(scanCount);
        uiScanTable.initScanRecordTable(scanRecordTable);
        // 动态生成列与属性的映射
        setupTableColumnMappings();

        // 设置 LocalDateTime 格式化
        qrCodeScanTimeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getFormattedQrCodeScanTime()));
        plcDataReturnTimeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getFormattedPlcDataReturnTime()));
    }

    private void setupTableColumnMappings() {
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(FXML.class) && TableColumn.class.isAssignableFrom(field.getType())) {
                try {
                    field.setAccessible(true);
                    @SuppressWarnings("unchecked")
                    TableColumn<CleaningData, ?> column = (TableColumn<CleaningData, ?>) field.get(this);
                    // 通过 fx:id 名称推导属性名
                    String propertyName = field.getName().replace("Column", "");
                    // 设置 CellValueFactory
                    column.setCellValueFactory(new PropertyValueFactory<>(propertyName));
                } catch (IllegalAccessException e) {
                    log.error("绑定 TableColumn '{}' 到属性失败。", field.getName(), e);
                }
            }
        }
    }

    // 复制
    @FXML
    public void doCopy(MouseEvent mouseEvent) {
        if (mouseEvent.getSource() instanceof Button) {
            scanText.selectAll();
            scanText.copy();
            uiLogger.info("复制成功。");
        }
    }

    // 编辑
    @FXML
    public void doEdit(MouseEvent mouseEvent) {
        if (mouseEvent.getSource() instanceof Button) {
            scanText.setEditable(true);
            uiLogger.info("已允许编辑。");
        }
    }

    // 入库
    @FXML
    public void doStorage(MouseEvent mouseEvent) {
        if (mouseEvent.getSource() instanceof Button) {
            scannerDataReceiver.handleReceivedData(scanText.getText(),false);
        }
    }

    // 自动入库勾选事件
    @FXML
    public void onActionAutoStorage(ActionEvent actionEvent) {
        if (actionEvent.getSource() instanceof CheckBox) {
            if (autoStorage.isSelected()) {
                storageBtn.setDisable(true);
                uiLogger.info("自动入库已开启。");
            } else {
                storageBtn.setDisable(false);
                uiLogger.info("自动入库已关闭。");
            }
        }
    }


    // 重置清空记录
    @FXML
    void resetScanCount(ActionEvent event) {
        CleaningData lastWaitingForTestResultData = uiScanTable.getPendingData();
        if (lastWaitingForTestResultData != null) {
            cleaningDataMapper.deleteById(lastWaitingForTestResultData.getId());
        }
        uiScanTable.clearScanRecords();
    }

}
